<?php
namespace app\controller;

use mailer\facade\Mailer;
use app\BaseController;
use think\facade\Cache;
use think\facade\Session;
use GuzzleHttp\Client;
use app\model\User;

class Api extends BaseController
{
    // 设置发送邮件的最小时间间隔(秒)
    const SEND_MAIL_INTERVAL = 60;

    public function msg()
    {
        // 验证TOKEN
        $token = $this->request->post('token', '');
        if (empty($token)) {
            return json([
                'code' => 400,
                'msg' => 'token不能为空！'
            ]);
        }
        // 用户表查询TOKEN是否存在
        $where = [
            'token' => $token,
            'status' => 1
        ];
        $user = User::where($where)->find();
        if (!$user) {
            return json([
                'code' => 400,
                'msg' => '不是授权用户，请联系管理员！',
                'token'=> $user
            ]);
        }


        // 获取POST数据
        $subject = $this->request->post('subject', '');
        $to = $user['email'];
        $content = $this->request->post('content', '');
        if (empty($subject) || empty($to) || empty($content)) {
            return json([
                'code' => 400,
                'msg' => '内容不能为空！'
            ]);
        }

        // 获取用户ID或会话ID作为缓存键的一部分
        $userId = Session::get('user_id', '');
        $sessionId = Session::getId();
        $cacheKey = 'last_send_mail_time_' . ($userId ?: $sessionId);

        // 获取上次发送邮件的时间戳
        $lastSendTime = Cache::get($cacheKey, 0);

        // 计算距离上次发送邮件的时间间隔
        $timeSinceLastSend = time() - $lastSendTime;

        if ($timeSinceLastSend >= self::SEND_MAIL_INTERVAL) {
            
            // 检查内容是否安全
            $check_content = $this->check_content_safe($content);
            if (!$check_content) {
                return json([
                    'code' => 400,
                    'msg' => '内容不安全，请重新编辑！'
                ]);
            }
            

            // 添加标题
            $subject = '【' . config('mailer.from.name') . '】' . $subject;
            // 发送邮件
            Mailer::to($to)
                ->subject($subject)
                ->html($content)
                ->send();

            // 记录当前发送时间
            Cache::set($cacheKey, time());

            // 记录发送次数到用户表
            $user->inc('send_count');


            return json([
                'code' => 200,
                'msg' => 'success'
            ]);
        } else {
            return json([
                'code' => 429,
                'msg' => '请求过于频繁,请稍后再试'
            ]);
        }
    }

    // 检测内容安全
    private function check_content_safe($content)
    {
        // 获得TOKEN
        $token = $this->get_access_token();
        $url = config('mailer.msgdefined.api').'?access_token=' . $token;
        // 发送请求
        $client = new Client([
            'verify' => false,
        ]);
        $response = $client->post($url, [
            'form_params' =>[
                'text' => $content,
                'scenes' => 'antispam',
                'data_type' => 'text'
            ]
        ]);
        $statusCode = $response->getStatusCode();
        if ($statusCode == 200) {
            $result = json_decode($response->getBody()->getContents(),true);
            if ($result['conclusionType'] == 1) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    // 获取 Access_token
    private function get_access_token()
    {
        // 检查鉴权TOKEN是否过期(有效期30天)
        if (Cache::get('baidu_access_token') ) {
            return Cache::get('baidu_access_token');
        }

        //  获取Access_token
        try{
            $client = new Client([
                'verify' => false,
            ]);
            // 获取POST数据
            $response = $client->post(config('mailer.baidu.token_api'), [
                'form_params' =>[
                    'client_id' => config('mailer.msgdefined.apikey'),
                    'client_secret' => config('mailer.msgdefined.apisecret'),
                    'grant_type' => 'client_credentials'
                ]
                
            ]);
            $statusCode = $response->getStatusCode();

            $token = $statusCode ==200? json_decode($response->getBody()->getContents(),true) :'';
            // 保存TOKEN到缓存中
            Cache::set('baidu_access_token', $token['access_token'], 2592000);
            return json($token['access_token']);
        }catch(GuzzleException $e){
            return json([
                'code' => 500,
                'msg' => '获取Access_token失败'
            ]);
        }
        
    }
}